Angle Between the Hands of a Clock
Understand and solve the interview question "Angle Between the Hands of a Clock."
We'll cover the following
Description#
Given two numbers, hour and minutes we will return the smaller angle (in degrees) formed between the hour and the minute hands on a clock.
Let’s look at some examples to better understand this:
1 of 2
2 of 2
Coding exercise#
Solution#
The idea is to separately calculate the angles between the 0-minutes vertical line and each hand. The answer will be the difference that is found between the two angles.
Note: Black lines in the clock represent the 0-minutes vertical lines.
Minute hand angle
Let’s start from the minute hand. The minute hand moves with 1 min intervals. At 1 min, the angle of the minute hand is 6°. . Since the whole circle of the clock is equal to 360° degrees and 60 minutes, we estimated that the minute hand moves 1 min = 360° / 60 = 6° degree with each minute.
Now, we can easily find an angle between the 0-minutes vertical line and a minute hand, using minutes_angle = minutes X 6°.
Hour hand angle
The hour hand moves with 1-hour intervals. The whole circle is equal to 360° degrees and 12 hours. So, the hour hand moves 1 hour = 360°/ 12 =30° degrees with each hour.
In the case of minutes = 0, we can easily find an angle between a 12-hour vertical line and an hour hand. We can use the following formula for this case:
hour_angle = hour X 30°
In the case of a 12-hour vertical line, the actual angle is zero. Therefore, we need to correct the expression to make it hour_angle = (hour mod 12) X 30°
Let’s consider another case, where minutes are greater than 0 (minutes > 0). In this case, we also have to consider the additional movement of the hour hand, where the hour hand moves forward slightly and jumps between the integer values, following the movement of the minute hand.
hour_angle = (hour mod 12 + minutes / 60) X 30°
Algorithm#
Here is how we will implement this feature:
-
First, we will initialize the constants,
one_min_angleandone_hour_angle, with the following values respectively:6,30. -
Then, we will initialize the
minutes_anglewith theminutes_angle = one_min_angle * minutesformula to find the angle between the minute hand and the 0-minutes vertical line. -
Next, we will initialize the
hour_anglewith thehour_angle = (hour % 12 + minutes / 60) * one_hour_angleformula to find the angle between the hour hand and the 12-hour vertical line. -
We will find the difference, using
difference = abs(hour_angle - minutes_angle). -
At the end, we will return the smallest angle:
min(difference, 360 - difference).
Let’s look at the code for this solution:
Complexity measures#
| Time complexity | Space complexity |
|---|---|
Time complexity#
The algorithm will have time complexity.
Space complexity#
The algorithm will have space complexity.
Pacific Atlantic Water Flow
Where to Go from Here?